package com.compty.paint.manager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang.math.RandomUtils;
import org.hibernate.Query;

import com.compty.core.framework.util.DateUtil;
import com.compty.core.hibernate.HibernateEntityDao;
import com.compty.core.page.Page;
import com.compty.paint.domain.CustomerInfo;
import com.compty.paint.domain.Delivery;
import com.compty.paint.domain.Goods;
import com.compty.paint.domain.Order;
import com.compty.paint.domain.OrderItem;
import com.compty.paint.domain.Painting;
import com.compty.paint.exception.OrderException;
import com.compty.paint.service.IUserService;
import com.compty.paint.service.UserServiceFactory;

public class OrderManager  extends HibernateEntityDao<Order>{
	
	private PaintingManager paintingManager;
	private GoodsManager goodsManager;
	
	public void setPaintingManager(PaintingManager paintingManager) {
		this.paintingManager = paintingManager;
	}

	public void setGoodsManager(GoodsManager goodsManager) {
		this.goodsManager = goodsManager;
	}

	/**
	 *@Todo:生成订单号 
	 *@author:朱庆辉
	 *@param customerInfo 当前客户
	 */
	public static String generateSequenceNo(CustomerInfo customerInfo){
		
		String sequenceNo = DateUtil.toString(Calendar.getInstance().getTime(), "yyMMddHHmmss");
		sequenceNo = sequenceNo + RandomUtils.nextInt() ;
		
		return sequenceNo;
	}
	
	public Page pageOrders(int pageNo, int pageSize) {
		IUserService userService = UserServiceFactory.getUserService();
		CustomerInfo member = userService.getCurrentMember();
		
		String hql = "from Order where customerInfo = ? order by id desc";
		Page page = super.pagedQuery(hql, pageNo, pageSize, member);
		return page;
	}
	
	
	public Order getOrder(Long order_id) {
		return super.get(order_id);
	}
	
	/**
	 * 由订单ID查询货运信息
	 * @param order_id 订单ID
	 */
	@SuppressWarnings("unchecked")
	public Delivery getOrderDelivery(Long order_id) {
		String hql = "from Delivery where order.id=?";
		List list = super.find(hql, order_id);
		if(list != null && list.size() >0){
			return (Delivery) list.get(0);
		}
		return null;
	}
	
	/**
	 * 由订单ID查询订单日志
	 * @param order_id 订单ID
	 */
	@SuppressWarnings("unchecked")
	public List listOrderLog(int order_id) {
		String hql = "from OrderLog where order.id = ?";
		List list = super.find(hql, order_id);
		list = list == null ? new ArrayList() : list;
		return list;
	}

	/**
	 * 由订单号查询订单明细
	 * @param order_id 订单ID
	 */
	@SuppressWarnings("unchecked")
	public List listGoodsItems(Integer order_id) {
		String hql = "from OrderItem where order.id = ?";
		List list = super.find(hql, order_id);
		list = list == null ? new ArrayList() : list;
		return list;
	}

	/**
	 * 分页查询未付订单
	 * @param curPage 当前页码
	 * @param pageSize 页码大小
	 * @param customerInfo 当前用户
	 */
	public Page listOrderNotPay(Integer curPage, Integer pageSize,CustomerInfo customerInfo) {
		String hql = "from OrderItem where order.customerInfo = ? and order.pay_status = 0 order by id desc ";
	    return super.pagedQuery(hql, curPage, pageSize, customerInfo);
	}

	/**
	 * 分页查询用户所有订单
	 * @param curPage 当前页码
	 * @param pageSize 页码大小
	 * @param customerInfo 当前用户
	 */
	public Page listAllOrder(Integer curPage, Integer pageSize,CustomerInfo customerInfo) {
		String hql = "from OrderItem where  order.customerInfo = ? order by id desc ";
	    return super.pagedQuery(hql, curPage, pageSize, customerInfo);
	}
	
	/***
	 * 查询总订单数
	 * @param member 当前登录用户
	 */
	public int queryTotalOrderCount(CustomerInfo member){
		
		String hql = "select count(*) as count from Order where customerInfo = ? ";
		Query query= createQuery(hql,member);
		int count=((Number)query.iterate().next()).intValue();
		return count;
	}
	
	/**查询已支付订单数**/
	public int queryPayedOrderCount(CustomerInfo member){
		
		String hql = "select count(*) as count from Order where customerInfo = ? and pay_status = 1";
		Query query = createQuery(hql,member);
		int count=((Number)query.iterate().next()).intValue();
		return count;
	}
	
	/**查询未支付订单数**/
	public int queryNotPayOrderCount(CustomerInfo member){
		
		String hql = "select count(*) as count from Order where customerInfo = ? and pay_status = 0";
		Query query = createQuery(hql,member);
		int count=((Number)query.iterate().next()).intValue();
		return count;
	}

	/**
	 * 由订单号查找订单
	 * @param order_no 订单号
	 */
	public Order findByOrderNo(String order_no) {
		return super.findUniqueBy("sequenceNo", order_no);
	}

	/**
	 * 保存订单至数据库
	 * @param order 订单
	 */
	public void saveOrder(Order order, CustomerInfo customerInfo, String gId,String num) throws OrderException{
		
		Integer number = Integer.valueOf(num);
		
		Integer goodsID = Integer.valueOf(gId);
		Goods goods = goodsManager.get(goodsID);
		
		/******************* 更新商品数量  begin ***********************/
		Integer store = goods.getStore();
		if( store != null ){
			if( store >= number ){
				goods.setStore(store-number);
			}
			else{
				throw new OrderException("该商品库存不足，请重新选择订购数量。");
			}
		}else{
			throw new OrderException("该商品无库存，请选购其他商品。");
		}
		goodsManager.save(goods);
		
		Long  painting_id = goods.getPainting_id();
		Painting painting = paintingManager.get(painting_id);
		painting.setStore(store-number);
		paintingManager.save(painting);
		/******************* 更新商品数量  end ***********************/
		
		/***************** 订单明细 begin  **************************/
		List<OrderItem> orderItems = new ArrayList<OrderItem>(0);
		OrderItem orderItem = new OrderItem();
		orderItem.setNum(number);
		orderItem.setShip_num(number);
		orderItem.setName(goods.getName());
		orderItem.setStore(goods.getStore());
		
		/***商品价格  begin ***/
		Double price = goods.getMktprice();
		if( price == null){
			price = goods.getPrice();
		}
		orderItem.setPrice(price);
		/***商品价格  end ***/
		
		orderItem.setSn(goods.getSn());
		orderItem.setBelongTo(painting.getEntryPerson().getId());
		orderItem.setGoods(goods);
		orderItem.setOrder(order);
		orderItems.add(orderItem);
		/****************** 订单明细   end *************************/
		
		/******************* 订单属性设置  begin ************************/
		order.setStatus(0);//未付款
		order.setPay_status(0);//未支付
		order.setShip_status(0);//未发货
		order.setDisabled(1);//可用，有效
		
		double orderAmount = calcOrderAmount(orderItems);//计算订单总价
		order.setOrder_amount(orderAmount);
		order.setGoods_amount(orderAmount);
		if("18922834841".equals(customerInfo.getUserName()) || "18925210869".equals(customerInfo.getUserName())){
			order.setOrder_amount(0.01);
			order.setGoods_amount(0.01);
		}
		
		/******************** 设置订单物流信息 begin ***************************/
//		order.setShip_addr(provinceInfo.getName()+cityInfo.getName()+customerInfo.getAddress());
		order.setShip_email(customerInfo.getEmail());
		order.setShip_mobile(customerInfo.getMobile());
		order.setShip_name(customerInfo.getCustomerName());
		order.setShip_tel(customerInfo.getTelphone());
		order.setShip_zip(customerInfo.getZipCode());
		order.setShipping_amount(0.0);
		order.setGoods_num(number);
		order.setGoods(painting.getTitle());
		/******************** 设置订单物流信息 end ***************************/
		
		order.setCustomerInfo(customerInfo);
		order.setModifyTime(Calendar.getInstance().getTime());
		order.setOrderTime(Calendar.getInstance().getTime());
		order.setOrderItems(orderItems);
		
		String sequenceNo = generateSequenceNo(customerInfo);//订单号
		order.setSequenceNo(sequenceNo);
		
		/******************* 订单属性设置  end ************************/
		
		super.save(order);
	}
	
	private double calcOrderAmount(List<OrderItem> orderItems) {
		if(orderItems == null) return 0.0;
		double orderAmount = 0.0;
		for (OrderItem orderItem : orderItems) {
			orderAmount += orderItem.getPrice() * orderItem.getNum();
		}
		return orderAmount;
	}

}
